package com.junxonline.instant.api.controller;

import cn.hutool.core.util.StrUtil;
import com.junxonline.instant.api.service.api.TerminalService;
import com.junxonline.instant.api.zookeeper.ZookeeperClient;
import com.junxonline.instant.common.annotation.ApiLog;
import com.junxonline.instant.common.entity.common.CommonResult;
import com.junxonline.instant.common.enumeration.ApiEnum;
import com.junxonline.instant.common.enumeration.ApiErrorEnum;
import com.junxonline.instant.common.enumeration.ApiVersionEnum;
import com.junxonline.instant.dao.entity.dto.common.TerminalServerDTO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 设备中心Controller
 *
 * @author JunX
 * @date 2021-06-24
 */
@Log4j2
@RestController
@RequestMapping(value = "/terminal")
public class TerminalController {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ZookeeperClient zookeeperClient;

    @Autowired
    private TerminalService terminalService;

    @ApiOperation(value = "获取设备中心节点")
    @ApiLog(label = "获取设备中心节点", type = ApiEnum.QUERY, version = ApiVersionEnum.V1)
    @PostMapping(value = "/getTerminalServerNode")
    public CommonResult getTerminalServerNode() {
        String terminalCode = request.getHeader("terminalCode");
        String sign = request.getHeader("sign");
        if (StrUtil.isBlank(terminalCode) || StrUtil.isBlank(sign)) {
            return CommonResult.fail(ApiErrorEnum.PARAMS_IS_NULL);
        }
        // 在经过认证拦截器后访问到该方法 可以视为通过认证直接签发Token
        String serverNode = zookeeperClient.getServerNode();
        String token = terminalService.login(terminalCode);
        return CommonResult.success(new TerminalServerDTO(serverNode, token));
    }

}
